package com.bwie.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbBrandMapper;
import com.bwie.mapper.TbMenuMapper;
import com.bwie.mapper.TbUserMapper;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TUser;
import com.bwie.pojo.TbBrand;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TUserService;
import com.bwie.mapper.TUserMapper;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import com.bwie.vo.LoginFrom;
import com.bwie.vo.PageInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.BodyElementType;
import org.bouncycastle.crypto.paddings.TBCPadding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author wx200
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-05-21 16:26:42
*/
@Service
@Slf4j
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{
    @Autowired
    TUserMapper tUserMapper;

    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    TbMenuMapper tbMenuMapper;

    @Autowired
    TbBrandMapper tbBrandMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    FastFileStorageClient fastFileStorageClient;



    /**
     * 登录
     * @return
     */
    @Override
    public Result login(LoginFrom login) {
//        获取当前用户信息是否存在
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbUser::getUserName,login.getUsername());
        TbUser tUser = tbUserMapper.selectOne(wrapper);
        if(tUser==null){
            return Result.error().setMsg("用户不存在");
        }
        String encrypt = MD5Utils.encrypt(login.getPassword());
      log.info("加密后的密码"+encrypt);
        if(!tUser.getUserPass().equals(encrypt)){
            return Result.error().setMsg("当前密码不正确");        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", tUser.getUserId()).claim("nickName",tUser.getNickName()).compact();
        System.out.println("真实姓名"+tUser.getNickName());
        tUser.setToken(token);
        stringRedisTemplate.opsForValue().set("token:"+tUser.getUserId(),token,60, TimeUnit.MINUTES);
        return Result.ok().setData(tUser);
    }

    @Override
    public Result getMenuTree(Integer userId) {
//        查询sql语句
       List<TbMenu> tbMenuList= tbMenuMapper.getMenuTree(userId);

        List<Tree<String>> build = TreeUtil.build(tbMenuList, "0", (menu, tree) -> {
            tree.setId(menu.getMenuId()+"");
            tree.setParentId(menu.getMenuPid()+"");
            tree.setName(menu.getMenuName());
            tree.putExtra("path",menu.getMenuPath());
        });
        return Result.ok().setData(build);
    }

    @Override
    public Result selectList(PageInfoVo pageInfoVo) {
        Page<TbUser> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
          wrapper.lambda().or().like(TbUser::getUserName,pageInfoVo.getKeyWord());
          wrapper.lambda().or().like(TbUser::getUserMobile,pageInfoVo.getKeyWord());
          wrapper.lambda().or().like(TbUser::getUserEmail,pageInfoVo.getKeyWord());
          wrapper.lambda().or().like(TbUser::getNickName,pageInfoVo.getKeyWord());
        }
        if(pageInfoVo.getGender()!=null){
            wrapper.lambda().eq(TbUser::getGender,pageInfoVo.getGender());
        }

        if(StringUtils.isNotEmpty(pageInfoVo.getBeginTime())){
            wrapper.lambda().ge(TbUser::getCreateTime,pageInfoVo.getBeginTime());
        }
        if(StringUtils.isNotEmpty(pageInfoVo.getEndTime())){
            wrapper.lambda().le(TbUser::getCreateTime,pageInfoVo.getEndTime());
        }
        Page<TbUser> tbUserPage = tbUserMapper.selectPage(page, wrapper);
        return Result.ok().setData(tbUserPage);
    }

    @Override
    public Result uploadFile(MultipartFile file) {
        try {
            String  extName = FileUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url="http://192.168.80.192:8888/"+storePath.getFullPath();
            return Result.ok().setData(url);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().setMsg("上传失败");
        }
    }

    @Override
    public Result updateFile(TbUser tbUser) {
         tbUserMapper.updateById(tbUser);
        return Result.ok();
    }

    @Override
    public Result getBrandList(PageInfoVo pageInfoVo) {
        Page<TbBrand> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
//     2.获取品牌列表 分页查询
        QueryWrapper<TbBrand> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
           wrapper.lambda().like(TbBrand::getBrandName,pageInfoVo.getKeyWord());
        }
        wrapper.lambda().orderByDesc(TbBrand::getCreateTime);
        Page<TbBrand> tbBrandPage = tbBrandMapper.selectPage(page, wrapper);
        return Result.ok().setData(tbBrandPage);
    }

    @Override
    public Result deleteById(Integer userId) {
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser==null){
            return Result.error().setMsg("用户不存在");
        }
//        单删
        tbUserMapper.deleteById(userId);
        return Result.ok();
    }

    /**
     * 批量删除
     * @param tbUserList
     * @return
     */
    @Override
    public Result deleteAll(List<TbUser> tbUserList) {
        for (TbUser tbUser : tbUserList) {
            tbUserMapper.deleteById(tbUser.getUserId());
        }
        return Result.ok();
    }

    @Override
    public Result checkUser(TbUser tbUser) {
        if(tbUser.getUserStatus()==2){
            if(StringUtils.isEmpty(tbUser.getReason())){
                return Result.error().setMsg("驳回原因不能为空");
            }
        }
//        判断用户是否存在
        TbUser user = tbUserMapper.selectById(tbUser.getUserId());
        if(user==null){
            return Result.error().setMsg("用户不存在");
        }
//        进行审核
        user.setUserStatus(tbUser.getUserStatus());
        user.setReason(tbUser.getReason());
        tbUserMapper.updateById(user);
        return Result.ok();
    }

    @Override
    public Result addBrand(TbBrand tbBrand) {
        String token = request.getHeader("token");
        if(token==null){
            return  Result.error().setMsg("请先登录");
        }
//        排重
        TbBrand one = tbBrandMapper.selectOne(new QueryWrapper<TbBrand>().lambda().eq(TbBrand::getBrandName, tbBrand.getBrandName()));
         if(one!=null){
             return Result.error().setMsg("品牌已存在");
         }

//         处理审核字段
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        String nickName = body.get("nickName", String.class);
        tbBrand.setCreateTime(new Date());
        tbBrand.setCreateBy(nickName);

        //         添加
        tbBrandMapper.insert(tbBrand);
        return Result.ok();
    }

}




